<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="query.query.orderNo" clearable placeholder="请输入订单编号" />
            <el-input v-model="query.query.customerName" clearable placeholder="请输入供应商名称" />
            <el-date-picker v-model="q_p_formDate1" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="daterange"
                range-separator="-" start-placeholder="申请开始日期" end-placeholder="申请结束日期"
                @change="q_p_selectTimecreate" />
            <el-button type="primary" icon="el-icon-search" @click="search">
                {{ $t("table.search") }}
            </el-button>
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
                生成对账单
            </el-button>
            <el-button type="primary" icon="el-icon-download" @click="handleExport">
                导出
            </el-button>
        </div>
        <el-table :data="tableData" row-key="id" highlight-current-row border
            :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
            @selection-change="handleSelectionChange">
            <!-- :selectable="selectableStatus" -->
            <el-table-column type="selection" width="55" />
            <el-table-column prop="statementCode" label="对账单单号" />
            <el-table-column prop="invoiceCode" label="发票号" />
            <el-table-column prop="inoutStoreNo" label="申请单号" />
            <el-table-column label="订单编号" prop="businessNo" />
            <el-table-column label="物料名称" prop="materialName" />
            <el-table-column label="物料编码" prop="materialNo" />
            <el-table-column prop="applyType" label="出库类型" align="center" width="80">
                <template slot-scope="{ row }">
                    <span>{{ getRkApplyType(row.applyType) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="inoutStoreNum" label="出库数量" align="center" width="80">
                <template slot-scope="{ row }">
                    <span :style="{'color':row.applyType == 8 ? 'red' : ''}">{{ row.inoutStoreNum }}</span>
                </template>
            </el-table-column>
            <el-table-column label="仓库" prop="fromWarehouseName" />
            <el-table-column label="客户名称" prop="partnerName" />
            <el-table-column prop="inoutStoreState" label="出库状态" align="center" width="80">
                <template slot-scope="{ row: { inoutStoreState,inOut } }">
                    {{ getInout(inOut, inoutStoreState) }}
                    <!-- {{ inOut == 1 && inoutStoreState == 0 ? "待入库" : "已入库" }} -->
                </template>
                <!-- <template slot-scope="{ row: { inoutStoreState } }">
                    {{ inoutStoreState == 0 ? "待出库" : "已出库" }}
                </template> -->
            </el-table-column>
            <el-table-column label="是否开票" prop="statementCode">
                <template slot-scope="{row:{statementCode}}">
                    {{ statementCode ? "是" : "否" }}
                </template>
            </el-table-column>
            <el-table-column label="订单日期" prop="orderDate">
                <template slot-scope="{ row }">
                    <span>{{ row.orderDate | parseTime("{y}-{m}-{d}") }}</span>
                </template>
            </el-table-column>
            <el-table-column label="出库申请时间" prop="applyTime">
                <template slot-scope="{ row }">
                    <span>{{
                        row.applyTime | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
                    }}</span>
                </template>
            </el-table-column>
            <el-table-column label="确认出库时间" prop="replyTime">
                <template slot-scope="{ row }">
                    <span>{{
                        row.replyTime | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
                    }}</span>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
            @pagination="getInfo" />
    </div>
</template>
<script>
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import {
    pageOutstoreList,
    accBillingSellOrder,
    accBindSellStatement,
    wmsStoreApplySellStatementList,
    accDetail2Export
} from "@/api/qmsQualityManagement";
import { sysInvoiceHeaderAll } from '@/api/invoice'
import { downfile, param } from "@/utils";

export default {
    name: "Project",
    components: { Pagination },
    directives: { waves },
    data() {
        return {
            q_p_formDate1: [],
            list: [],
            query: {
                pageIndex: 1,
                pageSize: 20,
                query: {
                    inOut: 2,
                    outStoreState: "1",
                    startDate: null,
                    endDate: null
                }
            },
            total: 0,
            dialogVisible: false,
            tableData: [],
            selectedList: [],
            inoutStoreNoList: [],
            materialList: [],
            userList: []
        };
    },
    computed: {},
    mounted() {
        this.getday()
        this.getInfo()
        this.getUserPage()
    },
    methods: {
        async handleExport() {
            try {
                if (!this.selectedList.length) {
                    this.$message.warning("请至少选择一条订单");
                    return;
                }
                let params = { ...this.query }
                params.pageSize = 100000
                params.query.ids = this.selectedList.join(',')
                await accDetail2Export(params)
            } catch (err) {
                const reader = new FileReader();
                reader.readAsText(err);
                reader.onload = (event) => {
                    const resultString = reader.result; // 这里就是转换后的字符串
                    if (resultString.includes('code') && resultString.includes('isSuccess')) {
                        this.$message.error(JSON.parse(resultString).message)
                    } else {
                        downfile('出库对账单明细.xlsx', err);
                    }
                }
            }
        },
        getInout(inOut, inoutStoreState) {
            if (inOut == 1) {
                return inoutStoreState == 1 ? '已入库' : '待入库'
            } else {
                return inoutStoreState == 1 ? '已出库' : '待出库'
            }
        },
        selectableStatus(row) {
            // return !row.statementCode
        },
        async getUserPage() {
            this.userList = await sysInvoiceHeaderAll(this.headerQuery)
        },
        handleAdd() {
            try {
                if (!this.selectedList.length) {
                    this.$message.warning("请至少选择一条订单");
                    return;
                }
                if (this.inoutStoreNoList.length) {
                    this.$message.error(`${this.inoutStoreNoList[0]}已生成对账单，不能重新生成,请重新选择！`)
                    return;
                }
                this.$confirm('此操作将生成对账单, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    await accBindSellStatement({
                        wmsStoreApplyIds: this.selectedList.join(',')
                    })
                    this.getInfo()
                    this.$message.success('操作成功！')
                })
            } catch (err) {

            }
        },
        async handleClick() {
            if (!this.selectedList.length) {
                this.$message.warning("请至少选择一条订单");
                return;
            }
            await accBillingSellOrder({ ids: this.selectedList.join(',') })
            this.$message.success('操作成功！')
            this.getInfo()
        },
        getRkApplyType(val) {
            if (val == 1) {
                return "销售出库";
            } else if (val == 2) {
                return "采购入库";
            } else if (val == 4) {
                return "调拨入库";
            } else if (val == 5) {
                return "调拨出库";
            } else if (val == 6) {
                return "其他入库";
            } else if (val == 7) {
                return "其他出库"
            } else if (val == 8) {
                return "销售退货入库";
            } else if (val == 9) {
                return "采购退货出库";
            }
        },
        getday() {
            // const currDate = new Date().toLocaleDateString()// 2020/11/6
            // const arrs = currDate.split('/')
            // const arrs1 = arrs.join('-')
            // this.query.query.beginDate = this.query.query.endDate = arrs1
            // this.q_p_formDate1 = [arrs1, arrs1]
            const currDate = new Date().toLocaleDateString()// 2020/11/6
            const arrs = currDate.split('/')
            const arrs1 = arrs.join('-')
            const yy = parseInt(arrs[0]);
            const mm = parseInt(arrs[1]);
            const dd = parseInt(arrs[2]);
            const pdStr = new Date(yy, mm - 1, 1).toLocaleDateString().split('/').join('-');
            this.query.query.startDate = pdStr
            this.query.query.endDate = arrs1
            this.q_p_formDate1 = [pdStr, arrs1]
        },
        q_p_selectTimecreate(val) {
            const { query } = this.query
            if (val) {
                query.startDate = val[0]
                query.endDate = val[1]
            } else {
                query.startDate = query.endDate = ''
            }
        },
        handleSelectionChange(e) {
            this.selectedList = [];
            this.inoutStoreNoList = [];
            e.forEach(item => {
                this.selectedList.push(item.idStr);
                if (item.statementCode) {
                    this.inoutStoreNoList.push(item.inoutStoreNo)
                }
            });
        },
        handleSizeChange(size) {
            this.query.pageSize = size;
            this.getInfo();
        },
        handleCurrentChange(currentPage) {
            this.query.pageIndex = currentPage;
            this.getInfo();
        },
        search() {
            this.query.pageIndex = 1;
            this.getInfo();
        },
        getInfo() {
            wmsStoreApplySellStatementList(this.query).then(res => {
                const { records, total } = res;
                this.tableData = records;
                this.total = total;
            });
        }
    }
};
</script>

<style scoped>
.addinput /deep/ .el-input__inner {
    border: none;
    background: #f5f7fa;
}

.addinput /deep/ .el-textarea__inner {
    border: none;
    background: #f5f7fa;
}

.downfile {
    text-decoration: underline;
    color: blue;
}
</style>